package com.translate.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.translate.common.*;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 *
 *@author ZXINHAO
 *@date 2023/3/15
*/
@Service
public class TranslateService implements InitializingBean {



    @Value("${baidu.translate.appid}")
    private String appid;

    @Value("${baidu.translate.secretKey}")
    private String secretKey;

    @Value("${baidu.translate.httpsUrl}")
    private String https_api;

    @Value("${baidu.translate.httpUrl}")
    private String http_api;

    private String from = "auto";

    private String to = "zh";

    //英->德->法->中
    private List<String> type_1 = Arrays.asList("en","de","jp","zh");
    //中->英->德->日->葡萄牙->中
    private List<String> type_2 = Arrays.asList("en","de","jp","pt","zh");
    //中->英->德->日->葡萄牙->意大利->波兰->保加利亚->爱沙尼亚->中
    private List<String> type_3 = Arrays.asList("en","de","jp","pt","it","pl","bul","est","zh");

    private Map<String,List<String>> languagesMap = new HashMap<String, List<String>>();
    /**
     *
     * @param query 查询内容
     * @param type 翻译等级(1初级,2中级,3高级)
     * @return
     */
    public AjaxResult transContent(String query,String type){
        String body = null;
        List<String> languages = languagesMap.get(type);
        if (languages == null) {
            return AjaxResult.error(ErrorEnum.SYSTEM_ERROR.getErrorMsg());
        }
        for (String  s : languages) {
            try {
                //防止频繁访问报错
                Thread.sleep(900);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            body = sendGet(buildParams(query, from, s));
            String response = parseResponse(body);
            query = response;
        }
        if(body == null){
            return AjaxResult.error(ErrorEnum.SYSTEM_ERROR.getErrorMsg());
        }
        //解析返回体
        String response = parseResponse(body);
        if(response == null){
            return AjaxResult.error(ErrorEnum.PARSE_ERROR.getErrorMsg());
        }
        return AjaxResult.success(response);
    }


    /**
     * 解析返回体
     * @param body
     * @return
     */
    private String parseResponse(String body){
        if(body.contains("error_code")){
            ErrorEnum[] values = ErrorEnum.values();
            ErrorEntity errorEntity = JSONUtil.toBean(body, ErrorEntity.class);
            Integer integer = Integer.valueOf(errorEntity.getError_code());
            for (ErrorEnum value : values) {
                Integer errorCode = value.getErrorCode();
                if(errorCode.equals(integer)){
                    //如果相同，返回错误信息
                    return value.getErrorMsg();
                }
            }
        }else{
            SuccessEntity successEntity = JSONUtil.toBean(body, SuccessEntity.class);
            List<SuccessEntity.TransResultDTO> transResult = successEntity.getTransResult();
            String dst = transResult.get(0).getDst();
            return dst;
        }
        return null;
    }


    /**
     * 构建请求参数
     * @param query
     * @param from
     * @param to
     * @return
     */
    private  String buildParams(String query,String from,String to) {

        //随机数
        int randomInt = RandomUtil.randomInt(1, 100);
        //签名
        String sign = SecureUtil.md5(appid + query + randomInt + secretKey);
        //将query设置为utf-8
        String encode = cn.hutool.core.net.URLEncoder.createDefault().encode(query, Charset.forName("UTF-8"));

        String url = http_api+"?"+"q="+encode+"&from="+from+"&to="+to+"&appid="+appid+"&salt="+randomInt+"&sign="+sign;

        return url;
    }

    /**
     * 发送get请求
     * @param params
     * @return
     */
    private String sendGet(String url){
        //发送请求
        HttpResponse execute = HttpUtil.createGet(url)
                //.form(params)
                .charset("UTF-8")
                .execute();
        return execute.body();
    }

    /**
     * 初始化参数
     * @throws Exception
     */
    public void afterPropertiesSet() throws Exception {
        languagesMap.put("1",type_1);
        languagesMap.put("2",type_2);
        languagesMap.put("3",type_3);
    }


}
